<uieip type="page" value="login" debug="true" timeout="5000"></uieip>
<uieip type="reg" value="data,http"></uieip>
<script runat="server">
    var action = request.param("action");
    var dbName = "yqbase";
    var tbName = "stock_list";
    var b_json = "{}";
    if (action == "dbs") {
        b_json = data.dbs();
    } else if (action == "title") {
        var tempno = request.param("tempno");
        b_json = data.title(dbName, tbName, tempno);
    } else if (action == "model") {
        var tempno = request.param("tempno");
        b_json = data.model(dbName, tbName, tempno);
    } else if (action == "select") {
        var where = request.param("where");
        var order = request.param("order");
        b_json = data.select(dbName, tbName, where, order);
    } else if (action == "paging") {
        var where = request.param("where");
        var order = request.param("order");
        var pageSize = request.param("pageSize");
        var pageNo = request.param("pageNo");
        b_json = data.paging(dbName, tbName, where, order, pageSize, pageNo);
    } else if (action == "query") {
        var sql = request.param("sql");
        b_json = data.query(dbName, tbName, sql);
    } else if (action == "row") {
        var keyid = request.param("keyid");
        var keyval = request.param("keyval");
        b_json = data.row(dbName, tbName, keyid, keyval);
    } else if (action == "foreignkey") {
        var json_ = request.param("json");
        b_json = data.foreignkey(json_);
    } else if (action == "action") {
        var json_ = request.param("json");
        b_json = data.action(dbName, tbName, JSON.parse(json_));
    } else if (action == "load_status") {
        b_json = data.query(dbName, "select from_date,end_date from stock_status");
    } else if (action == "load_data") {
        var res = http.get("http://127.0.0.1:8080/api/stock_list");
        if (res.error == 0) {
            b_json = data.exec(dbName, "update " + tbName + " set tag='1'");
            if (b_json.error == 0) {
                var a_data = [];
                for (var i = 0; i < res.data.length; i++) {
                    var row = res.data[i];
                    a_data.push({ action: "add", row: row });
                }
                b_json = data.action(dbName, tbName, a_data);
                if (b_json.error == 0) {
                    b_json = data.exec(dbName, `UPDATE stock_list AS new
SET 
  is_del = old.is_del,
  remark = old.remark
FROM stock_list AS old
WHERE 
  new.ts_code = old.ts_code
  AND old.tag = '1'
  AND new.tag IS NULL`);
                    if (b_json.error == 0) {
                        b_json = data.exec(dbName, "delete from " + tbName + " where tag='1'");
                    } else {
                        b_json = data.exec(dbName, "delete from " + tbName + " where  tag IS NULL");
                    }
                }
            }
        } else {
            b_json = res;
        }
    } else if (action == "load_cal") {
        var start_date = request.param("start_date");
        var end_date = request.param("end_date");
        b_json = http.get("http://127.0.0.1:8080/api/trade_cal?start_date=" + start_date + "&end_date=" + end_date);
    } else if (action == "load_daily") {
        try {
            var trade_date = request.param("trade_date");
            var res = http.get("http://127.0.0.1:8080/api/daily?trade_date=" + trade_date);
            var res_basic = http.get("http://127.0.0.1:8080/api/dailybasic?trade_date=" + trade_date);

            if (res.error == 0 && res.data.length > 0 &&
                res_basic.error == 0 && res_basic.data.length > 0
            ) {
                var a_data = [];
                for (var i = 0; i < res.data.length; i++) {
                    var _row = res.data[i];
                    a_data.push({ action: "add", row: _row });
                }

                var a_data_basic = [];
                for (var i = 0; i < res_basic.data.length; i++) {
                    var _row = res_basic.data[i];
                    a_data_basic.push({ action: "add", row: _row });
                }

                var from_date = parseYYYYMMDD(trade_date);
                from_date.setDate(from_date.getDate() - 180);
                from_date = formatYYYYMMDD(from_date);
                res = data.exec(dbName, "delete from stock_daily where trade_date<'" + from_date + "' or trade_date>='" + trade_date + "'");
                res_basic = data.exec(dbName, "delete from stock_dailybasic where trade_date<'" + from_date + "' or trade_date>='" + trade_date + "'");
                if (res.error == 0 && res_basic.error == 0) {
                    res = data.action(dbName, "stock_daily", a_data);
                    res_basic = data.action(dbName, "stock_dailybasic", a_data_basic);
                    if (res.error == 0 && res_basic.error == 0) {
                        res = data.query(dbName, "select * from stock_status");
                        if (res.error == 0) {
                            a_data = [];
                            if (res.rows.length == 0) {
                                a_data.push({ action: "add", row: { from_date: trade_date, end_date: trade_date } });
                            } else {
                                var _row = res.rows[0];
                                _row.end_date = trade_date;
                                a_data.push({ action: "upp", row: _row });
                            }
                            res = data.action(dbName, "stock_status", a_data);
                        }
                    }
                }
                b_json = res;
            } else {
                b_json = res;
            }
        }
        catch (e) {
            b_json = {
                error: 99,
                info: e.message
            };
        }
    } else if (action == "stock_daily") {
        var ts_code = request.param("ts_code");
        b_json = data.query(dbName, "select ts_code,trade_date,open,high,low,close,pre_close,change,pct_chg,vol,amount from stock_daily where ts_code='" + ts_code + "' order by trade_date");
    } else {
        b_json = {
            error: 99,
            info: action + "操作不存在。"
        };
    }

    response.write(JSON.stringify(b_json));

    // yyyyMMdd 转 Date
    function parseYYYYMMDD(dateString) {
        // 验证输入格式是否为8位纯数字
        if (typeof dateString !== 'string' || dateString.length !== 8 || !/^\d+$/.test(dateString)) {
            return new Date(NaN); // 返回无效日期
        }

        // 提取年月日并转为整数
        const year = parseInt(dateString.substring(0, 4), 10);
        const month = parseInt(dateString.substring(4, 6), 10) - 1; // 月份需减1（0-11）
        const day = parseInt(dateString.substring(6, 8), 10);

        // 创建日期对象
        const date = new Date(year, month, day);

        return date;
    }

    // 格式化为 yyyyMMdd（可选）
    function formatYYYYMMDD(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}${month}${day}`;
    }
</script>